<template>
	<div class="wrapper">
		<!-- 返回首页 -->
		<uni-bankhome />
		<div class="box">
			<div class="block block-1">
				<image class="img" src="@/pages/cart/static/pay.png" />
				<p class="ptips">收银台</p>
				<p class="ptips">剩余支付时间：
					<u-count-down :show-days="false" :show-border="true" font-size="28" color="#008ffa"
						border-color="#008ffa" ref="uCountDown" :timestamp="autoCancel"></u-count-down>
				</p>
				<p class="ptips">
					<span class="hb-money">支付金额：</span>
					<span class="hb-money">{{type=="RECHARGE"?"￥":""}}{{ cashierParams.price | unitPrice }}</span>
				</p>
			</div>
		</div>
		<div class="__pay_form__">
		</div>
		<div class="block-4" v-if="cashierParams.price > 0">
			<div class="payItem">支付方式</div>
			<div class="payItem" v-if='type=="RECHARGE"'>
				<u-row class="row" @click="awaitPay('WECHAT')">
					<div class="col1" size="100" style="text-align:left;">
						<div>
							<u-icon class="method_icon" name="weixin-circle-fill" color="#00c98b" size="80"></u-icon>
							<span class="method_name">微信</span>
						</div>
					</div>
					<div class="col3" textAlign="right">
						<u-icon size="26" color="#b1b1b1" name="arrow-right"></u-icon>
					</div>
				</u-row>
			</div>
			<div class="payItem" v-if='type=="ORDER"'>
				<u-row class="row" @click="awaitPay('WALLET','RECHARGE')">
					<div class="col1" size="100" style="text-align:left;">
						<div>
							<u-icon class="method_icon" name="red-packet-fill" color="#dd6161" size="80"></u-icon>
							<span class="method_name">余额钱包支付(当前余额：{{ walletValue | unitPrice }})</span>
						</div>
					</div>
					<div class="col3" textAlign="right">
						<u-icon size="26" color="#b1b1b1" name="arrow-right"></u-icon>
					</div>
				</u-row>
				<u-row class="row" @click="awaitPay('WALLET','PROMOTE')" v-if="walletPromoteValue>0">
					<div class="col1" size="100" style="text-align:left;">
						<div>
							<u-icon class="method_icon" name="red-packet-fill" color="#dd6161" size="80"></u-icon>
							<span class="method_name">佣金钱包支付(当前余额：{{ walletPromoteValue | unitPrice }})</span>
						</div>
					</div>
					<div class="col3" textAlign="right">
						<u-icon size="26" color="#b1b1b1" name="arrow-right"></u-icon>
					</div>
				</u-row>
				<u-row class="row" @click="awaitPay('WALLET','SALE')" v-if="walletSaleValue>0">
					<div class="col1" size="100" style="text-align:left;">
						<div>
							<u-icon class="method_icon" name="red-packet-fill" color="#dd6161" size="80"></u-icon>
							<span class="method_name">销售钱包支付(当前余额：{{ walletSaleValue | unitPrice }})</span>
						</div>
					</div>
					<div class="col3" textAlign="right">
						<u-icon size="26" color="#b1b1b1" name="arrow-right"></u-icon>
					</div>
				</u-row>
			</div>
		</div>
		<pay-password @passwordFinish="passwordFinish" ref="payPassword"></pay-password>
		<pay-methods @payChoose="payChoose" :hbMoney="cashierParams.price" :orderDetail="orderDetail" ref="payMethods"></pay-methods>
	</div>
</template>
<script>
	import * as API_Trade from "@/api/trade";
	import {
		payCallback
	} from '@/api/members'
	import {
		Recharge,
		RateSetting,
		CreatePartner,
		getUserInfo,
		cashierFee
	} from "@/api/members";
	import BigNumber from 'bignumber.js'
	import storage from "@/utils/storage.js";
	import payPassword from "@/components/pay-password/pay-password.vue"
	import payMethods from "@/components/pay-methods/pay-methods.vue"
	export default {
		components: {
			payPassword,
			payMethods
		},
		data() {
			return {
				orderDetail:{},
				type: '',
				//路径传参
				routerVal: "",
				//收银台参数
				cashierParams: "",
				//支付方式集合
				payList: "",
				//支付sn
				sn: "",
				//订单类型
				orderType: "",
				//支付异常
				exception: {},
				//支付表单
				payForm: {},
				//支付类型 APP/WECHAT_MP/H5/NATIVE app/微信小程序/h5/二维码
				paymentType: "",
				// 支付客户端 APP/NATIVE/JSAPI/H5
				paymentClient: "",
				//余额
				walletValue: 0.0,
				//销售余额
				walletSaleValue: 0.0,
				//佣金余额
				walletPromoteValue: 0.0,
				// 支付倒计时
				autoCancel: 0,
				trade_sn: '',
				orderTypesss: ''
			};
		},
		onLoad(val) {
			this.currentVip = val.vip
			this.type = val.orderType
			this.orderTypesss = val.orderTypesss
			this.trade_sn = val.trade_sn
			// 订单号，订单类型
			if (val.recharge_sn) {
				this.sn = val.recharge_sn;
				this.orderType = "RECHARGE";
			} else if (val.trade_sn) {
				this.sn = val.trade_sn;
				this.orderType = "TRADE";
			} else {
				this.sn = val.order_sn;
				this.orderType = "ORDER";
			}
			//初始化参数
			// #ifdef APP-PLUS
			this.paymentType = "APP";
			this.paymentClient = "APP";
			//#endif
			// #ifdef MP-WEIXIN
			this.paymentType = "WECHAT_MP";
			this.paymentClient = "MP";
			//#endif
		},
		onShow() {
			this.initHL()
		},
		mounted() {
			this.cashierData();
		},
		methods: {
			initHL() {
				let rate = storage.getVipRate();
				this.vipRate = rate
			},
			/**
			 * 选择支付方式的回调
			 * */
			payChoose(parameter) {
				if (parameter.method === 'wechat') {
					this.orderType = "RECHARGE"
					this.successPrice = parameter.rmbMoney
					if (parameter.rmbMoney > 0) {
						let params = {
							orderSn: this.orderSn,
							rechargeType: 6,
							price: parameter.rmbMoney,
							hbPrice: parameter.hbMoney,
						}
						Recharge(params).then((resRecharge) => {
							if (resRecharge.data.success) {
								this.pay({
									method: 'WECHAT',
									sn: resRecharge.data.result.rechargeSn
								})
							}
						});
					}
				}
			},
			/**
			 * 支付成功后跳转
			 */
			callback(paymentMethod) {
				let that = this
				if (paymentMethod === 'WECHAT') {
					if (that.orderTypesss == 'ORDER' || that.orderTypesss == 'TRADE') {
						uni.navigateTo({
							url: `/pages/cart/payment/payOrder?orderType=ORDER&trade_sn=${that.trade_sn}`
						});
					} else {
						uni.navigateTo({
							url: "/pages/cart/payment/success?" +
								"paymentMethod=" + paymentMethod +
								"&payPrice=" + this.successPrice +
								"&orderType=" + this.type
						});
					}
				} else {
					let payTotal = 0
					if (that.owner == 'SALE' || that.owner == 'PROMOTE') {
						payTotal = Number(that.cashierParams.memberPrice) + Number(that.cashierParams.commission || 0)
					} else {
						payTotal = Number(that.cashierParams.memberPrice)
					}
					uni.navigateTo({
						url: "/pages/cart/payment/success?paymentMethod=" +
							paymentMethod +
							"&payPrice=" +
							payTotal +
							"&orderType=" + this.type
					});
				}
			},
			initUserInfo() {
				//获取用户信息
				getUserInfo().then((user) => {
					storage.setUserInfo(user.data.result);
					storage.setHasLogin(true);
					uni.switchTab({
						url: "/pages/tabbar/user/my"
					})
				});
			},
			/**
			 * 获取收银详情
			 */
			cashierData() {
				let parms = {};
				parms.sn = this.sn;
				parms.orderType = this.orderType;
				parms.clientType = this.paymentType;
				parms.owner = 'RECHARGE'
				API_Trade.getCashierData(parms).then((res) => {
					if (res.data.success) {
						this.cashierParams = res.data.result;
						this.payList = res.data.result.support.filter((item) => {
							return item != "ALIPAY";
						});
						this.walletValue = res.data.result.walletValue;
						this.walletSaleValue = res.data.result.walletSaleValue;
						this.walletPromoteValue = res.data.result.walletPromoteValue;
						this.orderDetail.orderSn = res.data.result.orderSns;
						this.autoCancel = (res.data.result.autoCancel - new Date().getTime()) / 1000;
					} else if (res.data.code == 32000) {
						setTimeout(() => {
							uni.redirectTo({
								url: `/pages/order/myOrder?status=0`
							});
						}, 500)
					}
				});
			},
			awaitPay(payment, owner) {
				let that = this;
				that.$refs.payMethods.showMethodPopup()
				return
				const trade_sn = that.trade_sn
				that.owner = owner
				let payTotal = Number(that.cashierParams.memberPrice) + Number(that.cashierParams.commission)
				if (that.owner == 'SALE' || that.owner == 'PROMOTE') {
					if (that.cashierParams.commission === null) {
						that.cashierParams.commission = 0
					}
					uni.showModal({
						title: '提示',
						content: '商品金额：' + that.cashierParams.memberPrice + '        ' + '手续费：' + that
							.cashierParams.commission + '        ' + '实际支付金额:' +
							payTotal,
						success(res) {
							if (res.confirm) {
								if (payment == "WALLET") {
									if (that.owner == 'PROMOTE') {
										if (that.walletPromoteValue < payTotal) {
											uni.showModal({
												content: '余额不足以支付订单,请充值!',
												showCancel: false,
												confirmText: '去充值',
												success: function(resmodal) {
													if (resmodal.confirm) {
														uni.navigateTo({
															url: `/pages/mine/deposit/recharge?trade_sn=${trade_sn}&orderType=ORDER`
														})
													} else if (resmodal.cancel) {
														console.log('用户点击取消');
													}
												}
											})
											return;
										} else {
											that.$refs.payPassword.showPopup()
										}
									} else if (that.owner == 'SALE') {
										if (that.walletSaleValue < payTotal) {
											uni.showModal({
												content: '余额不足以支付订单,请充值!',
												showCancel: false,
												confirmText: '去充值',
												success: function(resmodal) {
													if (resmodal.confirm) {
														uni.navigateTo({
															url: `/pages/mine/deposit/recharge?trade_sn=${trade_sn}&orderType=ORDER`
														})
													} else if (resmodal.cancel) {
														console.log('用户点击取消');
													}
												}
											})
											return;
										} else {
											that.$refs.payPassword.showPopup()
										}
									}
								} else {
									this.pay(payment)
								}
							}
						}
					})
				} else {
					that.payModul(payment, owner)
				}
			},
			payModul(payment, owner) {
				this.owner = owner
				const trade_sn = this.trade_sn
				this.$u.throttle(() => {
					if (payment == "WALLET") {
						if (this.owner == 'RECHARGE') {
							if (this.walletValue < this.cashierParams.price) {
								uni.showModal({
									content: '余额不足以支付订单,请充值!',
									showCancel: false,
									confirmText: '去充值',
									success: function(resmodal) {
										if (resmodal.confirm) {
											uni.navigateTo({
												url: `/pages/mine/deposit/recharge?trade_sn=${trade_sn}&orderType=ORDER`
											})
										} else if (resmodal.cancel) {
											console.log('用户点击取消');
										}
									}
								})
								return;
							} else {
								this.$refs.payPassword.showPopup()
							}
						}
					} else {
						this.pay(payment)
					}
				}, 2000)
			},
			/**
			 * 钱包余额支付
			 * */
			passwordFinish(word) {
				this.pay('WALLET', word)
			},

			//订单支付
			async pay(parameter) {
				//支付方式 WECHAT/ALIPAY
				const paymentMethod = parameter.method;
				// 支付编号
				const sn = parameter.sn;
				// 交易类型【交易号|订单号】
				const orderType = this.orderType;
				const clientType = this.paymentType;
				const trade_sn = this.trade_sn
				let params = {
					sn,
					orderType,
					clientType,
					owner: this.owner
				};
				if (parameter.password) {
					params.paymentPassword = parameter.password
				}
				// 客户端类型 APP/NATIVE/JSAPI/H5
				const paymentClient = this.paymentClient;
				//微信小程序
				await API_Trade.initiatePay(paymentMethod, paymentClient, params).then(
					(res) => {
						let response = res.data.result;
						//如果支付异常
						if (!res.data.success) {
							uni.showModal({
								content: res.data.message,
								showCancel: false,
								confirmText: res.data.code === 34001 ? '去充值' : '确定',
								success: function(resmodal) {
									if (resmodal.confirm) {
										if (res.data.code === 34001) {
											uni.navigateTo({
												url: `/pages/mine/deposit/recharge?trade_sn=${trade_sn}&orderType=ORDER`
											})
										}
									} else if (resmodal.cancel) {
										console.log('用户点击取消');
									}
								}
							})
							return;
						}
						if (paymentMethod === "WECHAT") {
							uni.requestPayment({
								provider: "wxpay",
								appid: response.appid,
								timeStamp: response.timeStamp,
								nonceStr: response.nonceStr,
								package: response.package,
								signType: response.signType,
								paySign: response.paySign,
								success: (e) => {
									uni.showToast({
										icon: "none",
										title: "支付成功!",
									});
									this.callback(paymentMethod)
								},
								fail: (e) => {
									this.exception = e;
									uni.showModal({
										content: "支付失败,如果您已支付，请勿反复支付",
										showCancel: false,
									});
								},
							});
						} else {
							uni.showToast({
								icon: "none",
								title: "支付成功!",
							});
							this.callback(paymentMethod)
						}
					}
				);
			},
			isWeiXin() {
				var ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					return true;
				} else {
					return false;
				}
			},
		},
	};
</script>
<style scoped lang="scss">
	.method_icon {
		vertical-align: middle;
	}

	.method_name {
		font-size: 28rpx;
		color: #999;
		padding-left: 24rpx;
	}

	.row {
		display: flex;
		width: 100%;
	}

	/deep/ .u-row {
		width: 100% !important;
		display: flex;
		justify-content: space-between !important;
	}

	.method_name,
	.col1 {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.col1 {
		text-align: center;
		flex: 99;
	}

	.col3 {
		text-align: right;
		flex: 1;
	}

	.payItem {
		padding: 13px 25rpx;
		border-top: 1px solid #f9f9f9;

		line-height: 100rpx;
		font-size: 36rpx;
		color: #333;
	}

	.ptips {
		font-size: 32rpx;
		margin: 20rpx 0;
		color: #333;

		>span {
			font-size: 40rpx;
			color: #df5a52;
			margin-left: 10rpx;
			display: inline-block;
			height: 52upx;
			line-height: 52upx;
		}
	}

	.img {
		width: 392rpx !important;
		height: 296rpx !important;
	}

	.wrapper {
		min-height: 100vh;
		height: auto;
		background: #f9f9f9;
	}

	.block-4 {
		background: #fff;
		color: $u-tips-color;

		>p {
			padding: 8rpx;
		}
	}

	.box {
		background: #fff;
		padding: 40rpx 0;
		//   justify-content: center; //这个是X轴居中
		//   align-items: center; //这个是 Y轴居中
	}

	.block {
		text-align: center;
		display: block;
		width: 100%;

		image {
			width: 200rpx;
			height: 200rpx;
		}
	}

	.block-1 {
		margin-top: 80rpx;
	}

	.btns {
		margin: 0 20rpx;
	}
</style>
